import {createContext, ReactNode, useContext, useMemo, useState} from 'react';
import {QRCodeResult} from '../types/qrcode';
type ScannerContextType = {
  codeResult: QRCodeResult | undefined;
  setCodeResult: (value: QRCodeResult | undefined) => void;
};

const ScannerContext = createContext<ScannerContextType | undefined>(undefined);

export const useScannerProvider = (): ScannerContextType => {
  const context = useContext(ScannerContext);
  if (!context) {
    throw new Error(
      'useScannerProvider must be used within an ScannerProvider',
    );
  }
  return context;
};

export function ScannerProvider({
  children,
}: Readonly<{
  children: ReactNode;
}>) {
  const [codeResult, setCodeResult] = useState<QRCodeResult | undefined>();
  const contextValue = useMemo(
    () => ({
      codeResult,
      setCodeResult,
    }),
    [codeResult, setCodeResult],
  );

  return (
    <ScannerContext.Provider value={contextValue}>
      {children}
    </ScannerContext.Provider>
  );
}
